<?php
	class Admincp_UserController extends Main_Controller_Action
	{
		private $_arrParam;
		private $_model;
		private $_validate;
		
		public function init()
		{
			$this->loadTemplates('admin');
			$this->view->headTitle('Quản lý tài khoản');
			$this->_arrParam = $this->_request->getParams();
			$this->_model = new Admincp_Model_User();
			$this->_validate = new Admincp_Form_ValidateUser();
		}
		
		public function preDispatch()
		{
		    $auth = Zend_Auth::getInstance();
		    if(!$auth->hasIdentity()) {
		        if($this->_request->getActionName() != 'login')
		            $this->_redirect('admincp/index/login');
		    }
		}
		
		public function indexAction()
		{
			$adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->listUser());
			$paginator = new Zend_Paginator($adapter);
			$paginator->setItemCountPerPage(40);
			$paginator->setPageRange(5);
			$currentPage = $this->_request->getParam('page', 1);
			$paginator->setCurrentPageNumber($currentPage);
			$this->view->data = $paginator;
			$this->view->total = $paginator->getTotalItemCount();
			
			if($_POST['add']) {
			    $this->_redirect('admincp/user/create');
			}
			if($_POST['delete']) {
			    $listId = $this->_arrParam['check'];
			    $this->_model->deleteMultiUser($listId);
			    $this->_redirect($_SERVER['HTTP_REFERER']);
			}
		}
		
		public function createAction()
		{
		    if($this->_request->isPost()) {
		        $strTrim      = new Zend_Filter_StringTrim();
		        $email        = strtolower($strTrim->filter(strip_tags($this->_arrParam['email'])));
		        $password     = $strTrim->filter(strip_tags($this->_arrParam['password']));
		        $rePassword   = $strTrim->filter(strip_tags($this->_arrParam['rePassword']));
		        $fullname     = $strTrim->filter(strip_tags($this->_arrParam['fullname']));
		        $gender       = (int) $this->_arrParam['gender'];
                $birthday     = $strTrim->filter(strip_tags($this->_arrParam['birthday']));
                $role         = (int) $this->_arrParam['role'];
                $upload       = new Zend_File_Transfer_Adapter_Http();
                $info         = $upload->getFileInfo();
                $avatar       = $upload->getFileName('avatar', false);
                $this->view->roleValue = $role;
                $this->view->genderValue = $gender;
		        $flag = true;
		        
		        if(!$this->_validate->validPassword($password)) {
		            $this->view->errorPassword = 'Mật khẩu có độ dài từ 6-50 kí tự';
		            $flag = false;
		        }
		        if(!$this->_validate->validPassword($rePassword)) {
		            $this->view->errorRePassword = 'Mật khẩu có độ dài từ 6-50 kí tự';
		            $flag = false;
		        }
		        if($password != $rePassword) {
		            $this->view->errorRePassword = 'Mật khẩu không trùng khớp';
		            $flag = false;
		        }
		        if($this->_validate->validFullname($fullname)) {
		            $this->view->fullnameValue = $fullname;
		        }
		        else {
		            $this->view->errorFullname = 'Tên đầy đủ từ 1-50 kí tự chữ cái hoặc số';
		            $flag = false;
		        }
		        if($this->_validate->validEmail($email)) {
                    $this->view->emailValue = $email;
		        }
		        else {
		            $this->view->errorEmail = 'Email phải đúng định dạng';
		            $flag = false;
		        }
		        if($this->_model->checkUser(null, $email) == 0) {
		            $this->view->emailValue = $email;
		        }
		        else {
		            $this->view->errorEmail = 'Email này đã tồn tại';
		            $flag = false;
		        }
                if($this->_validate->validBirthday($birthday)) {
                    $this->view->birthdayValue = $birthday;
                }
                else {
                    $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (ngày-tháng-năm)';
                    $flag = false;
                }
                $upload->addValidator('Size', false, 410000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                if($this->_validate->validAvatar($avatar)) {
                    if(!$upload->isValid()) {
                        $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                        $flag = false;
                    }
                }
		        
		        if($flag == true) {
		            $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $common = new Admincp_Model_Common();
		            $code = time() . mt_rand(5, 99999999);
		            $data = array(
		                'email'=>$email,
		                'password'=>$this->genPassword($password),
		                'fullname'=>$fullname,
		                'gender'=>$gender,
                        'birthday'=>$common->formatDateToSql($birthday),
		                'code'=>$code,
                        'role'=>$role,
		                'status'=>1,
		                'fullname_plaintext'=>strtolower($strFlex->filter($fullname)),
		            );
                    if($this->_validate->validAvatar($avatar)) {
                        $resize = new Zend_Filter_ImageSize();
                        preg_match('#\.([^\.]+)$#', $avatar, $matches);
                        $fileExtension  = $matches[1];
                        $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                        $newFileName1 = $fileName . '.' . $fileExtension;
                        
                        $options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName1,'overwrite'=>true);
                        $upload->addFilter('Rename',$options,'avatar');
                        $upload->receive('avatar');
                        $output = $resize->setHeight(80)
                                        ->setWidth(80)
                                        ->setThumnailDirectory(BASE_PATH . '/public/files/user/')
                                        ->filter(BASE_PATH . '/public/files/user/' . $newFileName1);
                        header('Content-Type: image/jpeg');
                        $fh = fopen($output, 'r');
                        fpassthru($fh);
                        fclose($fh);
                        $newFileName = $fileName . '-80x80.' . $fileExtension;
                        unlink(PUBLIC_PATH . '/files/user/' . $newFileName1);
                        $data['avatar'] = $newFileName;
                    }
                    else {
                        $data['avatar'] = 0;
                    }
		            $this->_model->createUser($data);
		            $this->_redirect('admincp/user');
		        }
		    }
		}
		
		public function editAction()
		{
		    $id = (int) $this->_arrParam['id'];
		    $this->view->data = $this->_model->getUserById($id);
		    
		    if($this->_request->isPost()) {
		        $strTrim = new Zend_Filter_StringTrim();
		        $email = strtolower($strTrim->filter(strip_tags($this->_arrParam['email'])));
		        $fullname = $strTrim->filter(strip_tags($this->_arrParam['fullname']));
		        $password = $strTrim->filter(strip_tags($this->_arrParam['password']));
                $rePassword = $strTrim->filter(strip_tags($this->_arrParam['rePassword']));
                $gender = (int) $this->_arrParam['gender'];
                $birthday = $strTrim->filter(strip_tags($this->_arrParam['birthday']));
                $role = (int) $this->_arrParam['role'];
		        $status = (int) $this->_arrParam['status'];
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $avatar = $upload->getFileName('avatar', false);
		        $flag = true;

		        if(!$this->_validate->validFullname($fullname)) {
		            $this->view->errorFullname = 'Tên đầy đủ từ 1-50 kí tự chữ cái hoặc số';
		            $flag = false;
		        }
		        if(!$this->_validate->validEmail($email)) {
		            $this->view->errorEmail = 'Email phải đúng định dạng';
		            $flag = false;
		        }
                if($this->_model->checkUser($id, $email) > 0) {
		            $this->view->errorEmail = 'Email này đã tồn tại';
		            $flag = false;
		        }
                if(!$this->_validate->validBirthday($birthday)) {
                    $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (ngày-tháng-năm)';
                    $flag = false;
                }
                $upload->addValidator('Size', false, 410000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                if($this->_validate->validAvatar($avatar)) {
                    if(!$upload->isValid()) {
                        $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                        $flag = false;
                    }
                }
		        
		        if($flag == true) {
		            $code = time() . mt_rand(5, 99999999);
		            $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $common = new Admincp_Model_Common();
                    $data = array(
                        'email'=>$email,
                        'fullname'=>$fullname,
                        'gender'=>$gender,
                        'birthday'=>$common->formatDateToSql($birthday),
                        'code'=>$code,
                        'role'=>$role,
                        'status'=>$status,
                        'fullname_plaintext'=>strtolower($strFlex->filter($fullname)),
                    );
		            
		            if(($password != '')||($rePassword != '')) {
		                if(!$this->_validate->validPassword($password)) {
		                    $this->view->errorPassword = 'Mật khẩu có độ dài từ 6-50 kí tự';
		                    $flag = false;
		                }
		                if(!$this->_validate->validPassword($rePassword)) {
		                    $this->view->errorRePassword = 'Mật khẩu có độ dài từ 6-50 kí tự';
		                    $flag = false;
		                }
		                if($password != $rePassword) {
		                    $this->view->errorRePassword = 'Mật khẩu không trùng khớp';
		                    $flag = false;
		                }
		                
		                if($flag == true) {
		                    $data['password'] = $this->genPassword($password);
		                }
		            }
		            else if($this->_validate->validAvatar($avatar)) {
                        $resize = new Zend_Filter_ImageSize();
                        preg_match('#\.([^\.]+)$#', $avatar, $matches);
                        $fileExtension  = $matches[1];
                        $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                        $newFileName1 = $fileName . '.' . $fileExtension;
                        
                        $options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName1,'overwrite'=>true);
                        $upload->addFilter('Rename',$options,'avatar');
                        $upload->receive('avatar');
                        $output = $resize->setHeight(80)
                                        ->setWidth(80)
                                        ->setThumnailDirectory(BASE_PATH . '/public/files/user/')
                                        ->filter(BASE_PATH . '/public/files/user/' . $newFileName1);
                        header('Content-Type: image/jpeg');
                        $fh = fopen($output, 'r');
                        fpassthru($fh);
                        fclose($fh);
                        $newFileName = $fileName . '-80x80.' . $fileExtension;
                        unlink(PUBLIC_PATH . '/files/user/' . $newFileName1);
                        $data['avatar'] = $newFileName;
                        if(is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                            @unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                        }
                    }
		            
                    if($flag == true) {
	                    $this->_model->updateUser($data, $id);
		              $this->_redirect('admincp/user');
	                }
		        }
		    }
		}

		public function deleteAction()
		{
		    $id = (int) $this->_arrParam['id'];
		    $this->_model->deleteUser($id);
		    $this->_redirect($_SERVER['HTTP_REFERER']);
		}
		
		public function publishAction()
		{
		    $id = (int) $this->_arrParam['id'];
		    $status = (int) $this->_arrParam['status'];
		    $status = ($status == 1) ? 2 : 1;
		    $data = array(
		        'status' => $status,
		    );
		    $this->_model->updateUser($data, $id);
		    $this->_redirect($_SERVER['HTTP_REFERER']);
		}
		
		public function searchAction()
		{
		    $strTrim = new Zend_Filter_StringTrim();
		    $strFlex = new Zendvn_Filter_RemoveCircumflex();
		    $fullname = strtolower($strTrim->filter(strip_tags($this->_arrParam['fullname'])));
		    $email = strtolower($strTrim->filter($strFlex->filter(strip_tags($this->_arrParam['email']))));
            $gender = (int) $this->_arrParam['gender'];
		    $status = (int) $this->_arrParam['status'];
		    $this->view->keyword = array(
	            'fullname'=>$fullname,
	            'email'=>$email,
                'gender'=>$gender,
	            'status'=>$status,
		    );
		    $data = array(
	            'fullname'=>(string) '%'.str_replace(' ','%',$strFlex->filter($fullname)).'%',
	            'email'=>(string) '%'.str_replace(' ','%',$email).'%',
                'gender'=>$gender,
	            'status'=>$status,
		    );
		    $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->searchUser($data));
		    $paginator = new Zend_Paginator($adapter);
		    $paginator->setItemCountPerPage(40);
		    $paginator->setPageRange(5);
		    $currentPage = $this->_request->getParam('page', 1);
		    $paginator->setCurrentPageNumber($currentPage);
		    $this->view->data = $paginator;
		    $this->view->total = $paginator->getTotalItemCount();
		}
		
		public function profileAction()
		{
		    $auth = Zend_Auth::getInstance();
		    $infoUser= $auth->getIdentity();
		    $this->view->data = $this->_model->getUserById($infoUser->id);
		    
		    if($this->_request->isPost()) {
		        $strTrim = new Zend_Filter_StringTrim();
		        $fullname = $strTrim->filter(strip_tags($this->_arrParam['fullname']));
		        $email = $strTrim->filter(strtolower(strip_tags($this->_arrParam['email'])));
                $gender = $this->_arrParam['gender'];
                $birthday = $this->_arrParam['birthday'];
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $avatar = $upload->getFileName('avatar', false);
		        $flag = true;

		        if(!$this->_validate->validFullname($fullname)) {
		            $this->view->errorFullname = 'Tên đầy đủ từ 1-50 kí tự chữ cái hoặc số';
		            $flag = false;
		        }
                if(!$this->_validate->validBirthday($birthday)) {
                    $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (ngày-tháng-năm)';
                    $flag = false;
                }
                $upload->addValidator('Size', false, 410000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                if($this->_validate->validAvatar($avatar)) {
                    if(!$upload->isValid()) {
                        $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                        $flag = false;
                    }
                }
		        
		        if($flag == true) {
		            $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $common = new Admincp_Model_Common();
		            $code = time() . mt_rand(5, 99999999);
                    $birthday = $common->formatDateToSql($birthday);
		            $data = array(
                        'fullname'=>$fullname,
                        'gender'=>$gender,
                        'birthday'=>$birthday,
                        'code'=>$code,
		                'fullname_plaintext'=>strtolower($strFlex->filter($fullname)),
		            );
                    if($this->_validate->validAvatar($avatar)) {
                        $resize = new Zend_Filter_ImageSize();
                        preg_match('#\.([^\.]+)$#', $avatar, $matches);
                        $fileExtension  = $matches[1];
                        $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                        $newFileName1 = $fileName . '.' . $fileExtension;
                        
                        $options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName1,'overwrite'=>true);
                        $upload->addFilter('Rename',$options,'avatar');
                        $upload->receive('avatar');
                        $output = $resize->setHeight(80)
                                        ->setWidth(80)
                                        ->setThumnailDirectory(BASE_PATH . '/public/files/user/')
                                        ->filter(BASE_PATH . '/public/files/user/' . $newFileName1);
                        header('Content-Type: image/jpeg');
                        $fh = fopen($output, 'r');
                        fpassthru($fh);
                        fclose($fh);
                        $newFileName = $fileName . '-80x80.' . $fileExtension;
                        unlink(PUBLIC_PATH . '/files/user/' . $newFileName1);
                        $data['avatar'] = $newFileName;
                    }
                    
		            $this->_model->updateUser($data, $infoUser->id);
		            $this->_redirect('admincp/user/success');
		        }
		    }
		}
		
		public function changepasswordAction()
		{
		    if($this->_request->isPost()) {
		        $auth = Zend_Auth::getInstance();
		        $infoUser= $auth->getIdentity();
		        $this->view->data = $infoUser;
		        $strTrim = new Zend_Filter_StringTrim();
		        $oldPassword = $strTrim->filter($this->_arrParam['oldPassword']);
		        $password = $strTrim->filter($this->_arrParam['password']);
		        $rePassword = $strTrim->filter($this->_arrParam['rePassword']);
		        $flag = true;
		        
		        if(!$this->_validate->validPassword($oldPassword)) {
		            $this->view->errorOldPassword = 'Mật khẩu cũ có độ dài 6-50 kí tự';
		            $flag = false;
		        }
		        if(!$this->_validate->validPassword($password)) {
		            $this->view->errorPassword = 'Mật khẩu mới có độ dài 6-50 kí tự';
		            $flag = false;
		        }
		        if(!$this->_validate->validPassword($rePassword)) {
		            $this->view->errorRePassword = 'Nhập lại mật khẩu mới có độ dài 6-50 kí tự';
		            $flag = false;
		        }
		        if($password != $rePassword) {
		            $this->view->errorRePassword = 'Mật khẩu mới không trùng khớp';
		            $flag = false;
		        }
		        if($this->_model->checkPassword($infoUser->id, $this->genPassword($oldPassword)) == 0) {
		            $this->view->errorOldPassword = 'Mật khẩu cũ không chính xác';
		            $flag = false;
		        }
		        
		        if($flag == true) {
		            $data = array(
		                'password'=>$this->genPassword($password),
		            );
		            $this->_model->updateUser($data, $infoUser->id);
		            $this->_redirect('admincp/user/success');
		        }
		    }
		}
		
		public function successAction()
		{
		    $this->_helper->layout->setLayout('success');
		}
		
		public function genPassword($password)
		{
		    return md5('tivi'.$password);
		}
	}
